package com.cevent.community.app.system.controller.admin;/**
 * Created by Cevent on 2021/9/13.
 */

import com.cevent.community.app.common.domain.Member;
import com.cevent.community.app.common.dto.MemberDto;
import com.cevent.community.app.common.dto.ResponseDataDto;
import com.cevent.community.app.common.dto.SendMailDto;
import com.cevent.community.app.common.service.MemberService;
import com.github.pagehelper.IPage;
import com.sun.xml.internal.ws.db.glassfish.BridgeWrapper;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cevent
 * @description 会员接口层
 * @date 2021/9/13 15:23
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    public static final String BUSINESS_NAME="系统模块-会员业务";
    private static final Logger LOG= LoggerFactory.getLogger(MemberController.class);
    @Resource
    private MemberService memberService;

    @RequestMapping("/sendMail")
    public ResponseDataDto sendMail(){
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.sendSimpleMail());
        return responseData;
    }

    @PostMapping("/sendHtmlMail")
    public ResponseDataDto sendHtmlMail(@RequestBody SendMailDto sendMailDto){
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setResponseData(memberService.sendHtmlMail(sendMailDto));
        return responseData;
    }
    /** 用户登录
     * */
    @PostMapping("/loginIn")
    public ResponseDataDto loginIn(@RequestBody MemberDto memberDto, HttpServletRequest request){
        ResponseDataDto responseDataDto=new ResponseDataDto();
        LOG.info("传入的用户：{}",memberDto);
        /** 三次握手：
         * x-forwarded-for: HTTP 扩展头部
         * X-Forwarded-For: client, proxy1, proxy2
         * 经过了三个代理 Proxy1、Proxy2、Proxy3，IP 分别为 IP1、IP2、IP3
         * 1.用户真实 IP 为 IP0，那么按照 XFF 标准，服务端最终会收到以下信息：X-Forwarded-For: IP0, IP1, IP2
         * 2.Proxy3 直连服务器，它会给 XFF 追加 IP2，表示它是在帮 Proxy2 转发请求。
         * 3.列表中并没有 IP3，IP3 可以在服务端通过 Remote Address 字段获得。
         * Remote Address 来自 TCP 连接，表示与服务端建立 TCP 连接的设备 IP，在这个例子里就是 IP3。
         *
         */
        String ipAdd=request.getHeader("x-forwarded-for");
        String UNKNOWN="UNKNOWN";
        if(ipAdd==null || ipAdd.length()<1 ||UNKNOWN.equalsIgnoreCase(ipAdd)){
            ipAdd=request.getHeader("Proxy-Client-IP");
        }
        if(ipAdd==null || ipAdd.length()<1 ||UNKNOWN.equalsIgnoreCase(ipAdd)){
            ipAdd=request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAdd==null || ipAdd.length()<1 ||UNKNOWN.equalsIgnoreCase(ipAdd)){
            ipAdd=request.getRemoteAddr();
            String localIPv4="127.0.0.1";
            String localIPv6="0:0:0:0:0:0:0:1";
            if(localIPv4.equals(ipAdd) || localIPv6.equals(ipAdd)){
                //根据网卡取本机配置的ip
                InetAddress inet=null;
                try {
                    inet=InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if(inet!=null){
                    ipAdd=inet.getHostAddress();
                }
            }
        }
        //通过多个代理的情况，第一个ip为真实ip，多个ip按照,分割
        int i=15;
        String separators=",";
        if(ipAdd!=null && ipAdd.length()>i){
            if(ipAdd.indexOf(separators)>0){
                ipAdd=ipAdd.substring(0,ipAdd.indexOf(","));
            }
        }
        String deviceInfo= getDeviceInfo(request);
        //UserAgent应用
        String device=getDevice(request.getHeader("User-Agent"));
        responseDataDto.setResponseData(ipAdd+";设备信息："+deviceInfo+"格式化设备信息："+device);
        return responseDataDto;
    }

    private static String getDeviceInfo(HttpServletRequest request){
        String pattern1 = "^Mozilla/\\d\\.\\d\\s+\\(+.+?\\)";
        String pattern2 = "\\(+.+?\\)";
        ///将给定的正则表达式编译到模式中
        Pattern r = Pattern.compile(pattern1);
        Pattern r2 = Pattern.compile(pattern2);
        String userAgent=request.getHeader("User-Agent");

        //创建匹配给定输入与此模式的匹配器
        /*Matcher m = r.matcher(userAgent);
        String result = null;
        if (m.find()) {
            result = m.group(0);
        }
        if(result == null){
            return null;
        }
        Matcher m2 = r2.matcher(result);
        if (m2.find()) {
            result = m2.group(0);
        }
        result = result.replace("(", "");
        result = result.replace(")", "");

        if (StringUtils.isBlank(result)) {
            return null;
        }
        result = result.replace(" U;", "");
        result = result.replace(" zh-cn;", "");

        String android = "Android";
        String iPhone = "iPhone";
        String iPad = "iPad";
        if(result.contains(android) || result.contains(iPhone) || result.contains(iPad)){
            return "移动端";
        }else{
            return "PC端";
        }*/
        return userAgent;
    }
    /**
     * 解析 用户代理(User-Agent)
     * @param userAgent 用户代理User-Agent ,UA
     * @return "设备类型:%s,操作系统:%s,浏览器:%s,浏览器版本:%s,浏览器引擎:%s,用户代理(User-Agent):[%s]"
     */
    private String getDevice(String userAgent) {
        //解析agent字符串
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        //获取浏览器对象
        Browser browser = ua.getBrowser();
        //获取操作系统对象
        OperatingSystem os = ua.getOperatingSystem();
        LOG.info("浏览器对象信息：id: {}, name浏览器名称: {}, browserType浏览器类型: {}, renderingEngine浏览器引擎: {}, version浏览器版本: {},manufacturer浏览器制造商：{}",
                browser.getId(),browser.getName(),browser.getBrowserType(),browser.getRenderingEngine(),
                browser.getVersion(userAgent),browser.getManufacturer());
        LOG.info("操作系统对象：deviceType设备类型：{}, 操作系统：{},设备制造商：{}",os.getDeviceType(),os.getName(),os.getManufacturer());
        String userAgentStr=String.format(userAgent);
        if(userAgentStr.toLowerCase().contains("wechat")){
            LOG.info("登录方式：pc端微信登录");
        }
        return String.format("设备类型: %s,操作系统: %s,浏览器: %s,浏览器版本: %s,浏览器引擎: %s,用户代理(User-Agent):[%s]",
                os.getDeviceType(),
                os.getName(),
                browser.getName(),
                browser.getVersion(userAgent),
                browser.getRenderingEngine(),
                userAgent
        );
    }
}
